import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as path;

import '../../models/virtual_file_node.dart';
import '../../models/file_metadata.dart';
import '../../services/database_service.dart';
import '../../services/tianyi_cloud_service.dart';
import '../../services/file_manager_service.dart';
import '../../services/upload/upload_service.dart';
import '../../services/download/download_service.dart';
import '../../services/preferences_service.dart';

enum ViewMode {
  list,
  grid,
}

enum SortBy {
  name,
  size,
  type,
  modifiedTime,
}

enum SortOrder {
  ascending,
  descending,
}

class FileController extends GetxController {
  final DatabaseService _databaseService = Get.find<DatabaseService>();
  final TianyiCloudService _cloudService = Get.find<TianyiCloudService>();
  final FileManagerService _fileManagerService = Get.find<FileManagerService>();
  final UploadService _uploadService = Get.find<UploadService>();
  final DownloadService _downloadService = Get.find<DownloadService>();
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  
  // 当前文件列表
  final RxList<VirtualFileNode> _files = <VirtualFileNode>[].obs;
  List<VirtualFileNode> get files => _files;
  
  // 当前路径
  final RxString _currentPath = '/'.obs;
  String get currentPath => _currentPath.value;
  
  // 路径历史
  final RxList<String> _pathHistory = <String>['/'].obs;
  List<String> get pathHistory => _pathHistory;
  
  // 选中的文件
  final RxList<VirtualFileNode> _selectedFiles = <VirtualFileNode>[].obs;
  List<VirtualFileNode> get selectedFiles => _selectedFiles;
  
  // 视图模式
  final Rx<ViewMode> _viewMode = ViewMode.list.obs;
  ViewMode get viewMode => _viewMode.value;
  
  // 排序方式
  final Rx<SortBy> _sortBy = SortBy.name.obs;
  SortBy get sortBy => _sortBy.value;
  
  // 排序顺序
  final Rx<SortOrder> _sortOrder = SortOrder.ascending.obs;
  SortOrder get sortOrder => _sortOrder.value;
  
  // 搜索关键词
  final RxString _searchKeyword = ''.obs;
  String get searchKeyword => _searchKeyword.value;
  
  // 是否显示隐藏文件
  final RxBool _showHiddenFiles = false.obs;
  bool get showHiddenFiles => _showHiddenFiles.value;
  
  // 加载状态
  final RxBool _isLoading = false.obs;
  bool get isLoading => _isLoading.value;
  
  // 刷新状态
  final RxBool _isRefreshing = false.obs;
  bool get isRefreshing => _isRefreshing.value;
  
  // 选择模式
  final RxBool _isSelectionMode = false.obs;
  bool get isSelectionMode => _isSelectionMode.value;
  
  // 文件过滤器
  final RxString _fileFilter = ''.obs;
  String get fileFilter => _fileFilter.value;
  
  @override
  void onInit() {
    super.onInit();
    _loadPreferences();
    _setupListeners();
    loadFiles();
  }
  
  // 加载偏好设置
  void _loadPreferences() {
    _viewMode.value = _preferencesService.getViewMode();
    _sortBy.value = _preferencesService.getSortBy();
    _sortOrder.value = _preferencesService.getSortOrder();
    _showHiddenFiles.value = _preferencesService.getShowHiddenFiles();
  }
  
  // 设置监听器
  void _setupListeners() {
    // 监听文件管理器状态变化
    ever(_fileManagerService.currentPath.obs, (String path) {
      _currentPath.value = path;
      loadFiles();
    });
    
    ever(_fileManagerService.files.obs, (List<VirtualFileNode> files) {
      _updateFileList(files);
    });
  }
  
  // 加载文件列表
  Future<void> loadFiles() async {
    if (_isLoading.value) return;
    
    _isLoading.value = true;
    try {
      await _fileManagerService.loadFiles(_currentPath.value);
    } catch (e) {
      _showError('加载文件失败', e.toString());
    } finally {
      _isLoading.value = false;
    }
  }
  
  // 刷新文件列表
  Future<void> refreshFiles() async {
    if (_isRefreshing.value) return;
    
    _isRefreshing.value = true;
    try {
      await _fileManagerService.refreshCurrentDirectory();
    } catch (e) {
      _showError('刷新失败', e.toString());
    } finally {
      _isRefreshing.value = false;
    }
  }
  
  // 更新文件列表
  void _updateFileList(List<VirtualFileNode> files) {
    var filteredFiles = files;
    
    // 应用搜索过滤
    if (_searchKeyword.value.isNotEmpty) {
      filteredFiles = filteredFiles.where((file) => 
        file.name.toLowerCase().contains(_searchKeyword.value.toLowerCase())
      ).toList();
    }
    
    // 应用文件类型过滤
    if (_fileFilter.value.isNotEmpty) {
      filteredFiles = filteredFiles.where((file) => 
        file.isFolder || _matchesFileFilter(file, _fileFilter.value)
      ).toList();
    }
    
    // 应用隐藏文件过滤
    if (!_showHiddenFiles.value) {
      filteredFiles = filteredFiles.where((file) => 
        !file.name.startsWith('.')
      ).toList();
    }
    
    // 排序
    _sortFiles(filteredFiles);
    
    _files.value = filteredFiles;
  }
  
  // 文件类型匹配
  bool _matchesFileFilter(VirtualFileNode file, String filter) {
    final extension = path.extension(file.name).toLowerCase();
    
    switch (filter) {
      case 'image':
        return ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'].contains(extension);
      case 'video':
        return ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv'].contains(extension);
      case 'audio':
        return ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a'].contains(extension);
      case 'document':
        return ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt'].contains(extension);
      case 'archive':
        return ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'].contains(extension);
      default:
        return true;
    }
  }
  
  // 排序文件
  void _sortFiles(List<VirtualFileNode> files) {
    files.sort((a, b) {
      // 文件夹优先
      if (a.isFolder && !b.isFolder) return -1;
      if (!a.isFolder && b.isFolder) return 1;
      
      int result = 0;
      
      switch (_sortBy.value) {
        case SortBy.name:
          result = a.name.toLowerCase().compareTo(b.name.toLowerCase());
          break;
        case SortBy.size:
          if (a.isFolder && b.isFolder) {
            result = a.name.toLowerCase().compareTo(b.name.toLowerCase());
          } else {
            // 需要从文件元数据获取大小
            result = 0; // 暂时按名称排序
          }
          break;
        case SortBy.type:
          final aExt = path.extension(a.name).toLowerCase();
          final bExt = path.extension(b.name).toLowerCase();
          result = aExt.compareTo(bExt);
          if (result == 0) {
            result = a.name.toLowerCase().compareTo(b.name.toLowerCase());
          }
          break;
        case SortBy.modifiedTime:
          final aTime = a.updatedTime ?? a.createdTime;
          final bTime = b.updatedTime ?? b.createdTime;
          result = aTime.compareTo(bTime);
          break;
      }
      
      return _sortOrder.value == SortOrder.ascending ? result : -result;
    });
  }
  
  // 导航到文件夹
  Future<void> navigateToFolder(VirtualFileNode folder) async {
    if (!folder.isFolder) return;
    
    final newPath = folder.path;
    _pathHistory.add(newPath);
    await _fileManagerService.navigateToPath(newPath);
  }
  
  // 返回上级目录
  Future<void> navigateUp() async {
    if (_currentPath.value == '/') return;
    
    final parentPath = path.dirname(_currentPath.value);
    if (_pathHistory.length > 1) {
      _pathHistory.removeLast();
    }
    await _fileManagerService.navigateToPath(parentPath);
  }
  
  // 导航到指定路径
  Future<void> navigateToPath(String targetPath) async {
    _pathHistory.add(targetPath);
    await _fileManagerService.navigateToPath(targetPath);
  }
  
  // 搜索文件
  void searchFiles(String keyword) {
    _searchKeyword.value = keyword;
    _updateFileList(_fileManagerService.files);
  }
  
  // 清除搜索
  void clearSearch() {
    _searchKeyword.value = '';
    _updateFileList(_fileManagerService.files);
  }
  
  // 设置文件过滤器
  void setFileFilter(String filter) {
    _fileFilter.value = filter;
    _updateFileList(_fileManagerService.files);
  }
  
  // 切换视图模式
  void toggleViewMode() {
    _viewMode.value = _viewMode.value == ViewMode.list ? ViewMode.grid : ViewMode.list;
    _preferencesService.setViewMode(_viewMode.value);
  }
  
  // 设置排序方式
  void setSortBy(SortBy sortBy) {
    if (_sortBy.value == sortBy) {
      // 如果是同一个排序字段，切换排序顺序
      _sortOrder.value = _sortOrder.value == SortOrder.ascending 
          ? SortOrder.descending 
          : SortOrder.ascending;
    } else {
      _sortBy.value = sortBy;
      _sortOrder.value = SortOrder.ascending;
    }
    
    _preferencesService.setSortBy(_sortBy.value);
    _preferencesService.setSortOrder(_sortOrder.value);
    _updateFileList(_fileManagerService.files);
  }
  
  // 切换隐藏文件显示
  void toggleShowHiddenFiles() {
    _showHiddenFiles.value = !_showHiddenFiles.value;
    _preferencesService.setShowHiddenFiles(_showHiddenFiles.value);
    _updateFileList(_fileManagerService.files);
  }
  
  // 选择文件
  void selectFile(VirtualFileNode file) {
    if (_selectedFiles.contains(file)) {
      _selectedFiles.remove(file);
    } else {
      _selectedFiles.add(file);
    }
    
    _isSelectionMode.value = _selectedFiles.isNotEmpty;
  }
  
  // 全选
  void selectAll() {
    _selectedFiles.clear();
    _selectedFiles.addAll(_files);
    _isSelectionMode.value = true;
  }
  
  // 取消选择
  void clearSelection() {
    _selectedFiles.clear();
    _isSelectionMode.value = false;
  }
  
  // 上传文件
  Future<void> uploadFiles() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        allowMultiple: true,
        type: FileType.any,
      );
      
      if (result != null && result.files.isNotEmpty) {
        for (final platformFile in result.files) {
          if (platformFile.path != null) {
            final file = File(platformFile.path!);
            await _uploadService.addUploadTask(file, _currentPath.value);
          }
        }
        
        _showSuccess('上传任务已添加', '${result.files.length} 个文件已添加到上传队列');
      }
    } catch (e) {
      _showError('选择文件失败', e.toString());
    }
  }
  
  // 下载文件
  Future<void> downloadFile(VirtualFileNode file) async {
    if (file.isFolder) {
      _showError('不支持下载文件夹', '请选择具体的文件进行下载');
      return;
    }
    
    try {
      final metadata = await _databaseService.getFileMetadataByCloudId(file.fileMd5!);
      if (metadata != null) {
        await _downloadService.addDownloadTask(file, metadata);
        _showSuccess('下载任务已添加', '${file.name} 已添加到下载队列');
      } else {
        _showError('下载失败', '找不到文件元数据');
      }
    } catch (e) {
      _showError('下载失败', e.toString());
    }
  }
  
  // 批量下载
  Future<void> downloadSelectedFiles() async {
    if (_selectedFiles.isEmpty) return;
    
    final files = _selectedFiles.where((file) => !file.isFolder).toList();
    if (files.isEmpty) {
      _showError('没有可下载的文件', '请选择具体的文件进行下载');
      return;
    }
    
    try {
      for (final file in files) {
        final metadata = await _databaseService.getFileMetadataByCloudId(file.fileMd5!);
        if (metadata != null) {
          await _downloadService.addDownloadTask(file, metadata);
        }
      }
      
      _showSuccess('下载任务已添加', '${files.length} 个文件已添加到下载队列');
      clearSelection();
    } catch (e) {
      _showError('批量下载失败', e.toString());
    }
  }
  
  // 创建文件夹
  Future<void> createFolder(String name) async {
    try {
      await _fileManagerService.createFolder(_currentPath.value, name);
      _showSuccess('创建成功', '文件夹 "$name" 已创建');
      await refreshFiles();
    } catch (e) {
      _showError('创建文件夹失败', e.toString());
    }
  }
  
  // 重命名文件
  Future<void> renameFile(VirtualFileNode file, String newName) async {
    try {
      await _fileManagerService.renameFile(file, newName);
      _showSuccess('重命名成功', '"${file.name}" 已重命名为 "$newName"');
      await refreshFiles();
    } catch (e) {
      _showError('重命名失败', e.toString());
    }
  }
  
  // 删除文件
  Future<void> deleteFile(VirtualFileNode file) async {
    try {
      await _fileManagerService.deleteFile(file);
      _showSuccess('删除成功', '"${file.name}" 已删除');
      await refreshFiles();
    } catch (e) {
      _showError('删除失败', e.toString());
    }
  }
  
  // 批量删除
  Future<void> deleteSelectedFiles() async {
    if (_selectedFiles.isEmpty) return;
    
    try {
      for (final file in _selectedFiles) {
        await _fileManagerService.deleteFile(file);
      }
      
      _showSuccess('删除成功', '${_selectedFiles.length} 个文件已删除');
      clearSelection();
      await refreshFiles();
    } catch (e) {
      _showError('批量删除失败', e.toString());
    }
  }
  
  // 移动文件
  Future<void> moveFiles(List<VirtualFileNode> files, String targetPath) async {
    try {
      for (final file in files) {
        await _fileManagerService.moveFile(file, targetPath);
      }
      
      _showSuccess('移动成功', '${files.length} 个文件已移动');
      await refreshFiles();
    } catch (e) {
      _showError('移动失败', e.toString());
    }
  }
  
  // 复制文件
  Future<void> copyFiles(List<VirtualFileNode> files, String targetPath) async {
    try {
      for (final file in files) {
        await _fileManagerService.copyFile(file, targetPath);
      }
      
      _showSuccess('复制成功', '${files.length} 个文件已复制');
      await refreshFiles();
    } catch (e) {
      _showError('复制失败', e.toString());
    }
  }
  
  // 获取文件详情
  Future<Map<String, dynamic>?> getFileDetails(VirtualFileNode file) async {
    try {
      if (file.isFolder) {
        // 获取文件夹信息
        final children = await _databaseService.getFilesByParentId(file.id);
        return {
          'name': file.name,
          'type': '文件夹',
          'path': file.path,
          'created': file.createdTime,
          'updated': file.updatedTime,
          'children_count': children.length,
        };
      } else {
        // 获取文件信息
        final metadata = await _databaseService.getFileMetadataByCloudId(file.fileMd5!);
        return {
          'name': file.name,
          'type': '文件',
          'path': file.path,
          'size': metadata?.fileSize ?? 0,
          'mime_type': metadata?.mimeType ?? 'unknown',
          'md5': metadata?.md5,
          'created': file.createdTime,
          'updated': file.updatedTime,
        };
      }
    } catch (e) {
      _showError('获取文件详情失败', e.toString());
      return null;
    }
  }
  
  // 显示错误信息
  void _showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
  
  // 显示成功信息
  void _showSuccess(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  // 获取文件统计信息
  Map<String, dynamic> getFileStatistics() {
    final totalFiles = _files.where((f) => !f.isFolder).length;
    final totalFolders = _files.where((f) => f.isFolder).length;
    
    return {
      'total_files': totalFiles,
      'total_folders': totalFolders,
      'selected_count': _selectedFiles.length,
      'current_path': _currentPath.value,
      'view_mode': _viewMode.value.toString(),
      'sort_by': _sortBy.value.toString(),
      'sort_order': _sortOrder.value.toString(),
    };
  }
}